from django.shortcuts import render

from fruit import models
from fruit.models import User

# Create your views here.

#登录
def login_view(request):
    if request.method == "POST":
        user_name = request.POST.get('user_name','')
        pass_word = request.POST.get('pwd','')
        user = User.objects.filter(user_name=user_name)
        if user:
            if pass_word == user[0].pwd:
                request.session['IS_LOGIN'] = True
                request.session['user_name'] = user_name
                request.session['user_id'] = user[0].id
                # return index_view(request)
                return render(request, 'index.html')
            else:
                return render(request,'login.html',{'error':'用户密码错误！'})
        else:
            return render(request, 'login.html', {'error': '用户不存在！'})
    else:
        return render(request,'login.html')

#注册
def register_view(request):
    if request.method == "POST":
        user_name = request.POST.get("user_name")
        pwd = request.POST.get("pwd")
        cpwd = request.POST.get("cpwd")
        phone = request.POST.get("phone")
        print("==========oo"+user_name)
        user = User.objects.filter(user_name=user_name)
        print(user)
        if user:
            return render(request,"register.html",{"error":f"{user_name}已存在"})
        if pwd!=cpwd:
            return render(request, "register.html", {"error":"密码和确认密码不一样"})
        if len(user_name)>0 and len(pwd) > 0 and len(phone) > 0:
            user = User()
            user.user_name = user_name
            user.pwd = pwd
            user.phone = phone
            user.save()
            return  render(request,"login.html")
        else:
            return render(request,"register.html",{"error":"用户名、密码、手机号不能为空"})
    else:
        return render(request,"register.html")

#退出登录
def login_out(request):
    request.session.flush()
    return render(request,"login.html")


#首页
def index_view(request):
    types = models.Type.objects.all()
    dic = {}
    for type in types:
        list1 = models.Goode.objects.filter(type__id=type.id)
        dic[type.type_name] = list1
    return render(request,"index.html",
                  {"goods_type":types,"goods_type":dic,'user_name':request.session.get('user_name',None)})